package com.meepo.feed.comment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.ethanhua.skeleton.Skeleton
import com.ethanhua.skeleton.SkeletonScreen
import com.meepo.basic.router.RouterManager
import com.meepo.basic.components.ImagePopup
import com.meepo.basic.schema.Enums
import com.meepo.basic.schema.feed.CommentReq
import com.meepo.basic.schema.feed.Item
import com.meepo.basic.umeng.IShareListener
import com.meepo.basic.umeng.ShareContent
import com.meepo.basic.umeng.UMengManager
import com.meepo.basic.components.view.MeepoActivity
import com.meepo.feed.API
import com.meepo.feed.R
import com.meepo.feed.topic.TopicDetailActivity
import com.meepo.framework.design.desc.Data
import com.meepo.framework.design.helper.ImageLoader
import com.meepo.framework.design.helper.StatusBarHelper
import com.meepo.framework.design.input.InputDialog
import com.meepo.framework.design.userinfo.UserInfo
import com.meepo.sdk.utils.ActivityHelper
import com.xiaojinzi.component.anno.RouterAnno
import com.xiaojinzi.component.support.ParameterSupport
import kotlinx.android.synthetic.main.comment_activity_layout.*
import kotlinx.android.synthetic.main.feed_list_item_detail_action_part_layout.*
import kotlinx.android.synthetic.main.feed_list_item_detail_attitude_part_layout.*
import kotlinx.android.synthetic.main.item_title.*

@RouterAnno(hostAndPath = RouterManager.FeedModule.FeedComment_Path)
class CommentActivity : MeepoActivity() {

    private lateinit var mItem: Item

    private lateinit var itemId: String
    private var hideTopicView: Boolean = true

    private var mSkeletonScreen: SkeletonScreen? = null

    private var mCommentMainListFragment: CommentMainListFragment? = null

    @SuppressLint("SetTextI18n")
    private fun applyItem(item: Item?) {
        item?.let {

            mSkeletonScreen?.hide()

            mItem = item

            // 用户信息
            userinfo_view.setUserInfo(
                UserInfo(
                    username = item.author?.nickname ?: "",
                    avatar = item.author?.avatar ?: ""
                )
            )

            // 标题
            item_title_tv.text = item.title

            // 封面
            ImageLoader.loadImage(this, item.findOneCover(), iv_1)
            iv_1.setOnClickListener { ImagePopup.popup(this, iv_1, item.findOneCover()) }

            renderAttitudeView(item, 0, attitude_1_iv, attitude_1_tv, attitude_1_ll)
            renderAttitudeView(item, 1, attitude_2_iv, attitude_2_tv, attitude_2_ll)
            renderAttitudeView(item, 2, attitude_3_iv, attitude_3_tv, attitude_3_ll)
            renderAttitudeView(item, 3, attitude_4_iv, attitude_4_tv, attitude_4_ll)

            // 话题 分类
            topic_ll.visibility = if (hideTopicView) View.GONE else View.VISIBLE
            it.topic?.let { topic ->
                topic_info.setData(
                    Data(title = topic.title, avatar = topic.icon)
                )

                topic_rl.setOnClickListener { ActivityHelper.launch(this, TopicDetailActivity::class.java, "topicId", topic.id) }
            }

            // 分享
            share_count_tv.text = "" + (item.stat?.sharedCount ?: 0)
            share_ll.setOnClickListener { onShare(item) }
            share_iv2.setOnClickListener { onShare(item) }

            // 评论
            comment_count_tv.text = "" + (item.stat?.commentCount ?: 0)

            return
        }

        finish()
    }


    private fun onShare(item: Item) {
        UMengManager.shareWebByBoard(
            this,
            ShareContent(
                title = item.title ?: "",
                desc = item.title ?: "",
                url = item.h5?.content ?: "",
                iconPath = item.findOneCover()
            ),
            object : IShareListener {
                override fun onStart(media: String) {
                }

                @SuppressLint("SetTextI18n")
                override fun onResult(media: String) {
                    presenter.call(
                        API.instance().addAction(item.id, Enums.ITEM_TYPE_ITEM, Enums.ACTION_TYPE_SHARED, media),
                        {
                            item.stat?.incrShareCount()
                            share_count_tv.text = "" + (item.stat?.sharedCount ?: 0)
                        }
                    )
                }

                override fun onError(media: String, e: Throwable) {
                }

                override fun onCancel(media: String) {
                }
            })
    }

    @SuppressLint("SetTextI18n")
    private fun renderAttitudeView(item: Item, index: Int, imageView: ImageView, textView: TextView, container: LinearLayout) {
        val attitudeTextColor = this.resources.getColor(R.color.primary_color)

        item.attitudes?.let {
            if (it.size > index) {

                ImageLoader.loadImage(
                    this,
                    item.attitudes!![index].icon,
                    imageView,
                    requestOptions = RequestOptions().fitCenter().diskCacheStrategy(DiskCacheStrategy.ALL)
                )

                textView.text = "" + (item.stat?.getAttitudeCount(index) ?: 0)
                if (item.stat?.isAttitudeGiven(index) == true) {
                    textView.setTextColor(attitudeTextColor)
                }

                container.setOnClickListener {

                }
            }
        }
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {

        mSkeletonScreen = Skeleton.bind(item_detail_ll)
            .load(R.layout.comment_activity_skeleton_layout)
            .duration(1000)
            .angle(0)
            .show()


        itemId = ParameterSupport.getString(intent, "itemId", null)!!
        hideTopicView = ParameterSupport.getBoolean(intent, "hideTopicView", true)!!


        StatusBarHelper.immerse(this, header_rl)
        back_iv.setOnClickListener { finish() }

        refresh_layout.setEnableLoadMore(false)

        comment_input_layout.setOnClickListener {
            InputDialog("", object : InputDialog.InputListener {
                override fun onSubmit(inputText: String) {
                    presenter.call(
                        API.instance().addComment(CommentReq(itemId = itemId, content = inputText)),
                        { rsp -> rsp.data?.let { mCommentMainListFragment?.insert(it, 0) } },
                        {}
                    )
                }

                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                }

            }).show(supportFragmentManager, "aaa")
        }

        // 评论列表
        mCommentMainListFragment = CommentMainListFragment.instance(itemId)
//            RouterManager.FeedModule.routeToCommentList(itemId = itemId, listParams = ListParams(enablePullRefresh = false)) as CommentListFragment
        loadRootFragment(R.id.comment_list_frame, mCommentMainListFragment!!)
    }

    override fun initData() {
        presenter.call(
            API.instance().fetchDetail(itemId),
            { rsp -> applyItem(rsp.data) },
            { finish() }
        )
    }

    override fun setUpContentLayout(): Int = R.layout.comment_activity_layout

}